package com.zzyl.nursing.service.impl;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.IDCardUtils;
import com.zzyl.common.utils.PDFUtil;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.ai.BaiduAIProperties;
import com.zzyl.common.utils.ai.BaiduQianfanAIModelUtil;
import com.zzyl.nursing.DTO.HealthAssessmentDto;
import com.zzyl.nursing.vo.health.HealthReportVo;
import com.zzyl.oss.AliyunOSSOperator;
import org.intellij.lang.annotations.JdkConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.HealthAssessmentMapper;
import com.zzyl.nursing.domain.HealthAssessment;
import com.zzyl.nursing.service.IHealthAssessmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;



/**
 * 健康评估Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-11
 */
@Service
public class HealthAssessmentServiceImpl extends ServiceImpl<HealthAssessmentMapper, HealthAssessment> implements IHealthAssessmentService {
    @Autowired
    private HealthAssessmentMapper healthAssessmentMapper;
    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private BaiduQianfanAIModelUtil baiduQianfanAIModelUtil;

    /**
     * 查询健康评估
     *
     * @param id 健康评估主键
     * @return 健康评估
     */
    @Override
    public HealthAssessment selectHealthAssessmentById(Long id) {
        return getById(id);
    }

    /**
     * 查询健康评估列表
     *
     * @param healthAssessment 健康评估
     * @return 健康评估
     */
    @Override
    public List<HealthAssessment> selectHealthAssessmentList(HealthAssessment healthAssessment) {
        return healthAssessmentMapper.selectHealthAssessmentList(healthAssessment);
    }

    /**
     * 新增健康评估
     *
     * @param healthAssessment 健康评估
     * @return 结果
     */


    /**
     * 修改健康评估
     *
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public int updateHealthAssessment(HealthAssessment healthAssessment) {
        return updateById(healthAssessment) ? 1 : 0;
    }

    /**
     * 批量删除健康评估
     *
     * @param ids 需要删除的健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除健康评估信息
     *
     * @param id 健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentById(Long id) {
        return removeById(id) ? 1 : 0;
    }


    @Override
    public String upload(String idCardNo, MultipartFile file) throws Exception {
        //将文件存储到oss
        String upload = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());

        //读取pdf文件内容
        String pdfConntent = PDFUtil.pdfToString(file.getInputStream());
        if (StrUtil.isBlank(pdfConntent)) {
            throw new BaseException("报告为空");
        }

        //将文件内容存储到redis
        redisTemplate.opsForHash().put(CacheConstants.HEALTH_REPORT,idCardNo,pdfConntent);
        redisTemplate.expire(CacheConstants.HEALTH_REPORT, Duration.ofMinutes(5));
        return upload;
    }

    /**
     * 新增健康评估
     *
     * @param healthAssessment
     */
    @Override
    public Long insertHealthAssessment(HealthAssessmentDto healthAssessment) {
        //1.组装提示词
        String prompt = this.getPrompt(healthAssessment);
        //2.调用大模型分析报告返回结果，jSon模式
        String invoke = baiduQianfanAIModelUtil.invoke(prompt);
        //解析json格式的数据，保存数据库
        HealthReportVo aiReport = JSONUtil.toBean(invoke, HealthReportVo.class);

        //保存数据库
       Long id = this.saveHealthAssessment(aiReport,healthAssessment);

        //返回id
        return id;
    }

    private Long saveHealthAssessment(HealthReportVo aiReport, HealthAssessmentDto healthAssessment) {
        HealthAssessment healthAssessment1 = new HealthAssessment();
        //1.填写基本信息
        String idCard = healthAssessment.getIdCard();
        healthAssessment1.setElderName(healthAssessment.getElderName());
        healthAssessment1.setIdCard(idCard);
        healthAssessment1.setBirthDate(IDCardUtils.getBirthDateByIdCard(idCard));
        healthAssessment1.setAge(IDCardUtils.getAgeByIdCard(idCard));
        healthAssessment1.setGender(IDCardUtils.getGenderFromIdCard(idCard));
        //2老人的体检总结信息
        healthAssessment1.setTotalCheckDate(aiReport.getTotalCheckDate());
        healthAssessment1.setPhysicalExamInstitution(healthAssessment.getPhysicalExamInstitution());
        healthAssessment1.setPhysicalReportUrl(healthAssessment.getPhysicalReportUrl());
        //3.填充疾病风险
        double healthIndex = aiReport.getHealthAssessment().getHealthIndex();
        healthAssessment1.setHealthScore(String.valueOf(healthIndex));
        healthAssessment1.setRiskLevel(aiReport.getHealthAssessment().getRiskLevel());
        healthAssessment1.setSuggestionForAdmission(healthIndex > 60 ? 0 : 1);
        healthAssessment1.setNursingLevelName(getNursingLevelName(healthIndex));
        healthAssessment1.setAdmissionStatus(1);
        healthAssessment1.setAssessmentTime(LocalDateTime.now());
        healthAssessment1.setReportSummary(aiReport.getSummarize());

        healthAssessment1.setDiseaseRisk(JSONUtil.toJsonStr(aiReport.getRiskDistribution()));
        healthAssessment1.setAbnormalAnalysis(JSONUtil.toJsonStr(aiReport.getAbnormalData()));
        healthAssessment1.setSystemScore(JSONUtil.toJsonStr(aiReport.getSystemScore()));

        this.save(healthAssessment1);
        return healthAssessment1.getId();


    }

    private String getNursingLevelName(double healthIndex) {
if(healthIndex <0 || healthIndex >100){
      throw new BaseException("健康指数范围0-100");
}
        if (
                healthIndex>= 90
        ) {
            return "三级护理";
        } else if (
                healthIndex>= 80
        ) {
            return "二级护理";
        }else if (
                healthIndex>= 70
        ) {
            return "一级护理";
        }else if (
                healthIndex>= 60
        ) {
            return "特级护理";
        }

        return "不建议入住";
    }

    private String getPrompt(HealthAssessmentDto healthAssessment) {
       //1.先从redis中拿到体检报告，清除报告
        String report = (String) redisTemplate.opsForHash().get(CacheConstants.HEALTH_REPORT, healthAssessment.getIdCard());
        //2组装提示词
        String prompt = StringUtils.format(Constants.HEALTH_REPORT, report);
        //3.返回提示词
        return prompt;
    }
}
